package com.lemon.smartsafety.ui.activity.user;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.percent.PercentFrameLayout;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.ldzs.recyclerlibrary.anim.SlideInLeftAnimator;
import com.lemon.android.http.AesEncryptor;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.BuildConfig;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.event.base.AppEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.user.AutoLoginEvent;
import com.lemon.smartsafety.entity.event.user.DeleteUserEvent;
import com.lemon.smartsafety.entity.event.user.UpDateUserInfoEvent;
import com.lemon.smartsafety.entity.user.User;
import com.lemon.smartsafety.http.UrlInfo;
import com.lemon.smartsafety.http.callback.HandlerCallback.HttpFlow;
import com.lemon.smartsafety.http.service.UserServices;
import com.lemon.smartsafetynew.ui.activity.base.LemonPermissionListener;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.ui.adapter.user.LoginUserAdapter;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.AppUtils;
import com.lemon.smartsafety.utils.common.KeyBoardUtils;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.view.list.MultiStateView;
import com.lemon.safecloud.greendao.LoginUser;
import com.lemon.safecloud.greendao.LoginUserDao;
import com.nineoldandroids.animation.Animator;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushManager;
import com.tencent.android.tpush.service.XGPushService;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.dao.query.DeleteQuery;

/**
 * Created by Cooliean on 16/1/19.
 * 登录界面
 */
public class LoginActivity extends SwipeBackActivity {
    private static final int ANIM_DURATION = 500;

    @Bind(R.id.editUserName)
    MaterialEditText editUserName;

    @Bind(R.id.editUserPassword)
    MaterialEditText editUserPassword;

    @Bind(R.id.imageButtonDown)
    ImageButton imageButtonDown;

    @Bind(R.id.btnForgetPassword)
    Button btnForgetPassword;

    @Bind(R.id.chkSaveUser)
    AppCompatCheckBox chkSaveUser;

    @Bind(R.id.btnSubmit)
    Button btnSubmit;


    @Bind(R.id.btnRegister)
    Button btnRegister;

    @Bind(R.id.top_line)
    View mTopLine;


    private String loginName, loginPassword;

    /**
     * 提示信息对话框
     */
    private HUDUtil mHUDUtil;

    /**
     * 加密信息
     */
    private String mEncryptUP = "";


    private PopupWindow    mPopupWindow;
    private MultiStateView mMultiStateView;

    private PercentFrameLayout mPopParentLayout;

    private PullToRefreshRecyclerView mPullToRefreshRecyclerView;

    private LoginUserAdapter mAdapter;

    private List<LoginUser> mItems = new ArrayList<>();
    private View mOtherView;


    private LoginUserDao mLoginUserDao = AppService.getDBHelper().getDaoSession().getLoginUserDao();

    @Override
    protected int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initTitle() {
        this.setBarTitle(getString(R.string.login));
    }

    @Override
    protected void initViews() {
        super.initViews();
        mHUDUtil=new HUDUtil();
        mHUDUtil = mHUDUtil.init(LoginActivity.this);
        //mHUDUtil = HUDUtil.init(LoginActivity.this);

        if (BuildConfig.DEBUG) {
            editUserName.setText(Constants.TEST_USER_NAME);
            editUserPassword.setText(Constants.TEST_USER_PWD);
            chkSaveUser.setChecked(true);
        } else {
            editUserName.setText(mSharedPreferencesHelper.getLoginName());
        }

        if (mPopParentLayout == null) {//加载pop的内部视图
            mPopParentLayout = (PercentFrameLayout) getInflater().inflate(R.layout.pop_user_list, null);
            mPullToRefreshRecyclerView = (PullToRefreshRecyclerView) mPopParentLayout.findViewById(R.id.pullToRefreshRecyclerView);
            mPullToRefreshRecyclerView.setItemAnimator(new SlideInLeftAnimator());
            mPullToRefreshRecyclerView.getItemAnimator().setAddDuration(300);
            mPullToRefreshRecyclerView.getItemAnimator().setRemoveDuration(300);
            LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
            mPullToRefreshRecyclerView.setRefreshMode(Mode.DISABLED);


            mAdapter = new LoginUserAdapter(mItems);


            mPullToRefreshRecyclerView.setLayoutManager(layoutManager);
            mPullToRefreshRecyclerView.setAdapter(mAdapter);  // requires *wrapped* adapter


            mPullToRefreshRecyclerView.addHeaderView(getHeaderView(R.string.login_quick));

            mMultiStateView = (MultiStateView) mPopParentLayout.findViewById(R.id.multiStateView);


            mOtherView = mPopParentLayout.findViewById(R.id.vOther);
            mOtherView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    YoYo.with(Techniques.FadeOutRight).withListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            getPopWindow().dismiss();
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    }).duration(ANIM_DURATION).playOn(mMultiStateView);
                }
            });
        }

    }


    private PopupWindow getPopWindow() {
        KeyBoardUtils.closeSoftInput(this);
        if (mPopupWindow == null) {
            mPopupWindow = new PopupWindow(this);
            mPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            mPopupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            // 实例化一个ColorDrawable颜色为半透明
            mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            mPopupWindow.setFocusable(true);
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.setContentView(mPopParentLayout);
        }
        return mPopupWindow;
    }


    @Override
    protected void initListener() {
        btnSubmit.setOnClickListener(viewClickListener);
        imageButtonDown.setOnClickListener(viewClickListener);
        editUserName.setOnEditorActionListener(new TextView.OnEditorActionListener() {//限制不能输入换行符号
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
    }

    private View.OnClickListener viewClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.btnSubmit) {
                doSubmitAction();
            } else if (v.getId() == R.id.imageButtonDown) {

                YoYo.with(Techniques.FadeInRight).withListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        getPopWindow().showAsDropDown(mTopLine, 0, 0);
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        getAllSaveUser();
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                }).duration(ANIM_DURATION).playOn(mMultiStateView);
            }
        }
    };


    @OnClick({R.id.btnRegister})
    public void registerClick(View view) {
        UIHelper.showActivity(this, RegisterActivity.class);
    }

    @OnClick({R.id.btnForgetPassword})
    public void forgetClick(View view) {

        UIHelper.showActivity(this, VerifyUserEmailActivity.class);
        //mHUDUtil.showDeveloper();
    }


    /**
     * 获取所有缓存的用户
     */
    public void getAllSaveUser() {
        List<LoginUser> results = mLoginUserDao.queryBuilder().orderDesc(LoginUserDao.Properties.LogDate).list();

        if (results != null && !results.isEmpty()) {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            mItems.clear();
            mItems.addAll(results);
        } else {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        }
    }


    /**
     * 提交方法
     */
    private void doSubmitAction() {
        if (!validateForm()) return;
        /*
        checkPermission(getString(R.string.login_permission_tip), new LemonPermissionListener() {
            @Override
            public void onPermissionGranted() {
                doLogin();
            }

            @Override
            public void onPermissionDenied(ArrayList<String> deniedPermissions) {
                if (mHUDUtil != null) {
                    mHUDUtil.showErrorTip(getString(R.string.permission_denied_action));
                }

            }
        }, Manifest.permission.READ_PHONE_STATE);
        */

        checkPermission(getString(R.string.login_permission_tip), "", new LemonPermissionListener() {
            @Override
            public void onPermissionGranted(int requestCode) {
                doLogin();
            }

            @Override
            public void onPermissionDenied(int requestCode,ArrayList<String> deniedPermissions) {
                if (mHUDUtil != null) {
                    mHUDUtil.showErrorTip(getString(R.string.permission_denied_action));
                }
            }
        }, Manifest.permission.READ_PHONE_STATE);
    }

    private void doLogin() {
        //用户名、密码加密
        Log.i("tag1","haha password is " + loginPassword);
        mEncryptUP = AesEncryptor.encrypt(loginPassword);
        Log.i("tag1","encrypted  password is " + mEncryptUP);
        LemonRequestParams params = new LemonRequestParams();
        params.put("login_name", loginName);
        params.put("login_encrypt", mEncryptUP);
        params.put("device_id", AppUtils.getPhoneDeviceId(IApplication.context()));

        UserServices.init().doLogin(params);
    }


    /**
     * 表单验证
     *
     * @return
     */
    private boolean validateForm() {
        loginName = editUserName.getText().toString().trim();
        if (StringUtils.isEmpty(loginName)) {
            editUserName.setError(getString(R.string.login_name_is_null));
            return false;
        }
        loginPassword = editUserPassword.getText().toString();
        if (StringUtils.isEmpty(loginPassword)) {
            editUserPassword.setError(getString(R.string.login_password_is_null));
            return false;
        }
        return true;
    }

    @Override
    protected void callFinish() {
        mHUDUtil = null;
        mSharedPreferencesHelper = null;
        mLoginUserDao = null;
        mPopupWindow = null;
        mMultiStateView = null;
        mPopParentLayout = null;
        AppManager.getAppManager().finishActivity(LoginActivity.class);
    }

    private void callFinish(boolean isSuccess) {
        if (isSuccess) {
            AppEvent event = new AppEvent();
            event.setTag(LoginActivity.class.getName());
            AppService.getBus().post(event);//UserProfileFragment 给这里发送一个登录的事件
        }
        callFinish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mPopupWindow != null && mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();
                return true;
            } else {
                callFinish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe
    public void onEventMainThread(final HttpCallbackEvent<User> event) {
        if (UrlInfo.LOGIN.equals(event.getTag())) {
            if (event.getHttpFlow() == HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    //缓存用户信息
                    if (chkSaveUser.isChecked()) {
                        cacheLoginUser(event.getObj());
                    }
                    //修改手机本地的登录状态
                    setLoginState(event.getObj());
                    //通知主页刷新个人信息
                    AppService.getBus().post(new UpDateUserInfoEvent());

                    mHUDUtil.showDoneTip(getString(R.string.login_success), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            try {
                                bindPNSTag(event.getObj());
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                callFinish(true);
                            }
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }


    @Subscribe
    public void onEventMainThread(final DeleteUserEvent event) {
        if (EventTag.TAG_DELETE_LOGIN_USER_EVENT.equals(event.getTag())) {
            new MaterialDialog.Builder(this).content(R.string.is_delete)
                                            .positiveText(R.string.sure_str)
                                            .negativeText(R.string.cancel_str)
                                            .onAny(new MaterialDialog.SingleButtonCallback() {
                                                @Override
                                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                                    if (which == DialogAction.POSITIVE) {
                                                        LoginUser tempUser = mItems.remove(event.getPosition());
                                                        mLoginUserDao.delete(tempUser);
                                                        mAdapter.notifyItemRemoved(event.getPosition());
                                                        if (mItems.isEmpty()) {
                                                            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                                                        } else {
                                                            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                                                        }
                                                    }
                                                }
                                            })
                                            .show();
        }
    }


    @Subscribe
    public void onEventMainThread(final AutoLoginEvent event) {/* 这里是点击缓存用户后的回调 */
        if (EventTag.TAG_AUTO_LOGIN_EVENT.equals(event.getTag())) {
            YoYo.with(Techniques.FadeOutLeft).withListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    getPopWindow().dismiss();
                    editUserName.setText(event.getUser().getUserName());
                    editUserPassword.setText(event.getUser().getUserPassword());
                    doSubmitAction();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            }).duration(ANIM_DURATION).playOn(mMultiStateView);
        }
    }


    /**
     * 缓存需要记住保存用户名和密码的登录帐号
     *
     * @param user
     */
    public void cacheLoginUser(User user) {
        DeleteQuery deleteQuery = mLoginUserDao.queryBuilder()
                                               .where(LoginUserDao.Properties.UserName.eq(user.getLoginName()))
                                               .buildDelete();
        deleteQuery.executeDeleteWithoutDetachingEntities();
        LoginUser loginUser = new LoginUser(null, loginName, loginPassword, new Date());
        mLoginUserDao.insert(loginUser);
    }

    public void setLoginState(User user) {
        mSharedPreferencesHelper.setUserId(user.getUserId());
        mSharedPreferencesHelper.setUserName(user.getUserName());
        mSharedPreferencesHelper.setLoginName(user.getLoginName());
        mSharedPreferencesHelper.setLoginPassword(loginPassword);
        mSharedPreferencesHelper.setUserPhotoUrl(user.getPhotoUrl());
        mSharedPreferencesHelper.setIsLogin(true);
        mSharedPreferencesHelper.setDevicesId(AppUtils.getPhoneDeviceId(IApplication.context()));
        mSharedPreferencesHelper.setEncryptLoginInfo(mEncryptUP);
        mSharedPreferencesHelper.setUserType(user.getUserType());
        mSharedPreferencesHelper.setPlaceId(user.getPlaceId());
        mSharedPreferencesHelper.setUserPlaceInfo(user.getPlaceName());
        mSharedPreferencesHelper.setUserTypeName(StringUtils.nullValue(user.getUserTypeName()));
        mSharedPreferencesHelper.setRayEyeUrl(StringUtils.nullValue(user.getEyeUrl()));
        mSharedPreferencesHelper.setEmail(StringUtils.nullValue(user.getEmail()));
        mSharedPreferencesHelper.setEmailValidate(StringUtils.nullValue(user.getEmail_verify()));
    }

    /**
     * 绑定推送服务要用到的Tag
     *
     * @param user
     */
    private void bindPNSTag(final User user) {
        // 注册接口
        new Handler().post(new Runnable() {
            @Override
            public void run() {

                XGPushManager.registerPush(getApplicationContext(), user.getUserId(), new XGIOperateCallback() {
                    @Override
                    public void onSuccess(Object o, int i) {
                        Log.e("TPush", "注册成功，设备token为：" + o);
                    }

                    @Override
                    public void onFail(Object o, int errCode, String msg) {
                        Log.e("TPush", "注册失败，错误码：" + errCode + ",错误信息：" + msg);
                    }
                });

                LoggerHelper.error(getClass(), "user.getUserId();    " + user.getUserId());
                // 2.36（不包括）之前的版本需要调用以下2行代码
                Intent service = new Intent(getApplicationContext(), XGPushService.class);
                getApplicationContext().startService(service);
            }
        });
    }

}
